package com.rui.study.micro.userself.controller;

import com.rui.study.commons.model.BizException;
import com.rui.study.commons.model.Result;
import com.rui.study.commons.util.JsonUtil;
import com.rui.study.commons.util.RandomUtil;
import com.rui.study.commons.util.StringUtil;
import com.rui.study.micro.userself.external.api.TestAPI;
import com.rui.study.micro.userself.mapper.AccountMapper;
import com.rui.study.micro.userself.model.MailWrapper;
import com.rui.study.micro.userself.model.SmsSendingInfo;
import com.rui.study.micro.userself.util.RedisLock;
import com.rui.study.micro.userself.util.StatusCode;
import com.rui.study.test.enabled.Foo;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import static com.rui.study.micro.userself.util.Constant.USERNAME_NUMBER;

/**
 * @program: study
 * @description:
 * @author: Yaowr
 * @create: 2018-11-07 16:52
 **/
@RestController
@RefreshScope
public class TestController {

    @Autowired
    TestAPI testAPI;

    @Value("${msgcenter.mail.notification.exchange}")
    private String mailNotificationExchange;

    @Value("${msgcenter.mail.notification.routing_key_1}")
    private String routingKey1;

    @Value("${msgcenter.mail.notification.routing_key_2}")
    private String routingKey2;

    @Autowired
    private AccountMapper accountMapper;

    @Resource(name = "redisTemplate")
    private HashOperations<Serializable, String, String> hashRedisOps;

    @Autowired
    private RedisLock lock;

    private final AmqpAdmin amqpAdmin;
    private final AmqpTemplate amqpTemplate;

    @Autowired
    private Foo foo;

    @Autowired
    public TestController(AmqpAdmin amqpAdmin, AmqpTemplate amqpTemplate) {
        this.amqpAdmin = amqpAdmin;
        this.amqpTemplate = amqpTemplate;
    }


    @GetMapping("/v1/test")
    public Result test1() {
        Result response;
        try {
            String template = "【伏羲云】欢迎使用伏羲云，验证码是：" + RandomUtil.nextDigital(6) + ", 请在十分钟内完成注册";
            response = testAPI.testSend("BJJS002257", "jycm2017@", "", "", "15013659191", URLEncoder.encode(template, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            throw new BizException(StatusCode.SYSTEM_EXCEPTION);
        }
        return response;
    }

    @GetMapping("/v2/test")
    public Result test2() {
        /* 短信接口 */
        SmsSendingInfo smsSendingInfo = new SmsSendingInfo();
        smsSendingInfo.setCorpId("BJJS002257");
        smsSendingInfo.setPwd("jycm2017@");
        smsSendingInfo.setCell("");
        smsSendingInfo.setSendTime("");
        smsSendingInfo.setMobile("15013659191");

        String template = "【伏羲云】欢迎使用伏羲云，验证码是：" + RandomUtil.nextDigital(6) + ", 请在十分钟内完成注册";
        try {
            smsSendingInfo.setContent(URLEncoder.encode(template, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            throw new BizException(StatusCode.SYSTEM_EXCEPTION);
        }
        Result response = testAPI.testSend2(smsSendingInfo);
        return response;
    }

    @GetMapping("/v1/test/send-msg")
    public Result testSendMsg(@RequestParam("routingKey") String routingKey) {
        switch (routingKey) {
            case "0":
                routingKey = "";
                break;
            case "1":
                routingKey = routingKey1;
                break;
            case "2":
                routingKey = routingKey2;
                break;
        }
        amqpTemplate.convertAndSend(mailNotificationExchange, routingKey, JsonUtil.encode(buildMail()));
        return new Result();
    }

    @GetMapping("/v1/test/send-msg/with-rec")
    public Result test4() {
        Object result = amqpTemplate.convertSendAndReceive(mailNotificationExchange, routingKey1, JsonUtil.encode(buildMail()));
        return new Result(StatusCode.SUCCEED, result);
    }

    @GetMapping("/v1/uname-number")
    public Result getUnameNumber() {
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String number = new DecimalFormat("000000").format(hashRedisOps.increment(USERNAME_NUMBER, date, 1));;
        return new Result(StatusCode.SUCCEED, number);
    }

    @DeleteMapping("/v1/uname-number")
    public Result delUnameNumber() {
        return new Result(StatusCode.SUCCEED, hashRedisOps.getOperations().delete(USERNAME_NUMBER));
    }

    @DeleteMapping("/v1/account/{identify}")
    public Result delAccount(@PathVariable("identify") String identify) {
        return new Result(StatusCode.SUCCEED, accountMapper.delete(identify));
    }

    @DeleteMapping("/v1/lock/{method}")
    public Result delLock(@PathVariable("method") String method) {
        lock.unlock(method);
        return new Result(StatusCode.SUCCEED);
    }

    @PostMapping("/v1/test/feign")
    public Result testFeign() {
//        testAPI.testFeign("xxx", "11111111111111",
//                "G2101", "2", "yao@mpreader.com", "13112344321");
//        testAPI.testFeign("xxx", "11111111111111",
//                "G2101", "", "", "13112344321");      // 字段的值为""，
        testAPI.testFeign("xxx", "11111111111111",
                "G2101", null, null, "13112344321");    // 字段的值为原字符串{email}，没有变量替换
//        testAPI.testFeign("cc");
//        testAPI.testFeign("abc",  (byte) 1, null, "cc");
        return new Result(StatusCode.SUCCEED);
    }

    @GetMapping("/v1/test/enable-foo")
    public Result<Long> testEnabledFoo() {
        return new Result<>(StatusCode.SUCCEED, foo.bar());
    }


    private MailWrapper buildMail() {
        MailWrapper mailWrapper = new MailWrapper();
        mailWrapper.setSubject("注册验证码");
        mailWrapper.setContent("【伏羲云】欢迎注册伏羲云，验证码为" + RandomUtil.nextDigital(6) + "，请勿泄露于他人，并在十分钟内完成验证！");
        mailWrapper.setTos(new String[]{"yaowr@mpreader.com"});
        return  mailWrapper;
    }
}
